﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using Windows.UI.Xaml.Media.Imaging;

using RaisingStudio.SmallProgram.Library.Internal;

namespace RaisingStudio.SmallProgram.Library
{
    [SmallProgramType]
    public static class ImageList
    {
        private static Dictionary<string, BitmapSource> _savedImages = new Dictionary<string, BitmapSource>();

        public static Primitive LoadImage(Primitive fileNameOrUrl)
        {
            if (fileNameOrUrl.IsEmpty)
            {
                return "";
            }
            string name = Shapes.GenerateNewName("ImageList");
            _savedImages[name] = LoadImageFromFile(fileNameOrUrl);
            return name;
        }

        internal static BitmapImage LoadImageFromFile(Primitive fileNameOrUrl)
        {
            Primitive localFileName = Network.GetLocalFile(fileNameOrUrl);
            return (BitmapImage)SmallProgramApplication.InvokeWithReturn(delegate
            {
                try
                {
                    return new BitmapImage(new Uri((string)localFileName));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                    return null;
                }
            });
        }

        internal static BitmapSource GetBitmap(Primitive imageName)
        {
            BitmapSource image = null;
            if (!imageName.IsEmpty)
            {
                _savedImages.TryGetValue((string)imageName, out image);
            }
            if (image == null)
            {
                image = LoadImageFromFile(imageName);
            }
            return image;
        }

        public static Primitive GetHeightOfImage(Primitive imageName)
        {
            BitmapSource image = GetBitmap(imageName);
            if (image == null)
            {
                return 0;
            }
            return (Primitive)GraphicsWindow.InvokeWithReturn(() => image.PixelHeight);
        }

        public static Primitive GetWidthOfImage(Primitive imageName)
        {
            BitmapSource image = GetBitmap(imageName);
            if (image == null)
            {
                return 0;
            }
            return (Primitive)GraphicsWindow.InvokeWithReturn(() => image.PixelWidth);
        }
    }
}

